<template>
  <div>
    <a-breadcrumb>
      <a-breadcrumb-item>文章管理</a-breadcrumb-item>
      <a-breadcrumb-item>文章列表</a-breadcrumb-item>
    </a-breadcrumb>

    <div class="table-line">
      <div class="table-ops">
        <a-button
          type="primary"
          style="margin-top: 6px"
          @click="$router.push({ name: 'BackendBlogEdit' })"
        >
          <template #icon>
            <icon-plus />
          </template>
          创建文章
        </a-button>
      </div>

      <div class="table-filter" style="margin-top: 6px">
        <a-input-search
          v-model="params.keywords"
          placeholder="请输入文章标题"
          class="kw-input"
          @search="searchArticles"
          @keyup.enter="searchArticles"
        />
      </div>
    </div>

    <a-table
      :data="data.item"
      :loading="listBlogLoading"
      :pagination="{
        total: data.total,
        showTotal: true,
        showMore: true,
        showJumper: true,
        showPageSize: true,
        current: params.page_number,
        pageSize: params.page_size,
        onChange: (page_number) => {
          params.page_number = page_number
          fetchBlogList()
        }
      }"
      style="margin-top: 6px; width: 100%; border-radius: 8px; overflow: hidden"
    >
      <template #columns>
        <a-table-column title="编号" dataIndex="id" key="id" :width="50" align="center" />
        <a-table-column
          title="创建时间"
          dataIndex="created_at"
          key="time"
          :width="150"
          align="center"
        >
          <template #cell="{ record }">
            {{ dayjs.unix(record.created_at).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </a-table-column>
        <a-table-column
          title="更新时间"
          dataIndex="updated_at"
          key="time"
          :width="150"
          align="center"
        >
          <template #cell="{ record }">
            {{ dayjs.unix(record.updated_at).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </a-table-column>
        <a-table-column title="作者" dataIndex="author" key="title" :width="50" align="center" />
        <a-table-column title="标题" dataIndex="title" key="title" :width="150" align="center" />
        <a-table-column title="状态" dataIndex="status" key="status" :width="50" align="center">
          <template #cell="{ record }">
            {{ STATUS_MAP[record.status] }}
          </template>
        </a-table-column>
        <a-table-column title="操作" dataIndex="action" key="action" :width="300" align="center">
          <template #cell="{ record }">
            <div style="display: flex; justify-content: center; gap: 8px">
              <a-button type="outline" status="normal" size="small" @click="editArticle(record)">
                <template #icon>
                  <icon-edit />
                </template>
                编辑
              </a-button>
              <a-button type="outline" status="normal" size="small" @click="publishArticle(record)">
                <template #icon>
                  <icon-upload />
                </template>
                发布
              </a-button>

              <a-popconfirm
                :content="`否确认要删除[${record.title}]这篇文章?`"
                type="warning"
                :ok-loading="deleteLoadding"
                @ok="deleteArticle(record)"
              >
                <a-button type="primary" status="danger" size="small">
                  <template #icon>
                    <icon-delete />
                  </template>
                  删除
                </a-button>
              </a-popconfirm>
            </div>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { LIST_BLOG, DELETE_BLOG } from '@/api/vblog'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { Notification } from '@arco-design/web-vue'

// 响应式数据
const data = ref({ total: 0, item: [] })
const listBlogLoading = ref(false)
const params = ref({ keywords: '', page_number: 1, page_size: 10 })
const $router = useRouter()

// 获取文章列表
const fetchBlogList = async () => {
  listBlogLoading.value = true // 开始加载
  try {
    const res = await LIST_BLOG({
      ...params.value,
      page_number: params.value.page_number,
      page_size: params.value.page_size
    })
    if (res && res.data) {
      console.log(params.value)
      console.log(res.data)
      data.value = res.data // 更新数据
    } else {
      console.error('Invalid data structure:', res)
    }
  } catch (error) {
    console.error('Error fetching blog list:', error)
  } finally {
    listBlogLoading.value = false // 结束加载
  }
}

// 搜索文章
const searchArticles = () => {
  params.value.page_number = 1
  fetchBlogList()
}

// 编辑文章
const editArticle = (record) => {
  console.log(record)
  $router.push({ name: 'BackendBlogEdit', query: { id: record.id } })
  // 这里可以添加编辑文章的逻辑
}

// 发布文章
const publishArticle = (record) => {
  // 这里可以添加发布文章的逻辑
}

// 删除文章
const deleteLoadding = ref(false)
const deleteArticle = async (record) => {
  try {
    deleteLoadding.value = true // 开始加载状态
    await DELETE_BLOG(record.id) // 调用删除 API
    Notification.success({
      title: '删除成功',
      content: '文章删除成功'
    })
    await fetchBlogList() // 删除成功后刷新文章列表
  } catch (error) {
    Notification.error({
      title: '删除失败',
      content: '删除文章时发生错误，请重试。'
    })
    console.error('Error deleting article:', error) // 打印错误信息
  } finally {
    deleteLoadding.value = false // 结束加载状态
  }
}

// 在组件挂载时调用
onMounted(fetchBlogList)

const STATUS_MAP = {
  0: '草稿',
  1: '已发布',
  2: '已删除'
}
</script>

<style lang="css" scoped>
.table-line {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.table-ops {
  margin-bottom: 6px;
}

.table-filter {
  display: flex;
  align-items: center;
}

.kw-input {
  width: 200px;
}
</style>
